package com.arch.flink.biz.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author pizhihui
 * @date 2020-07-30
 */
public class WordCountDemo {


    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> ds = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<Tuple2<String, Integer>> so = ds.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] s1 = s.split(" ");
                for (String s2 : s1) {
                    out.collect(Tuple2.of(s2, 1));
                }
            }
        }).keyBy(0)
                .sum(1);


        so.print();

        env.execute("wordcount demo");


    }

}
